package com.bungarus.config;

import com.bungarus.codec.protobuf.MessageProtobuf;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 *
 * Created by tang on 2018/11/25.
 */
abstract public class ChannelServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        initCodecHandlers(socketChannel);
        initNormalHandlers(socketChannel);
        initServerServiceHandlers(socketChannel);
    }

    /**
     * init handlers as server listening to request from remote clients
     * @param socketChannel socketChannel
     */
    protected abstract void initServerServiceHandlers(SocketChannel socketChannel);

    /**
     * init handlers for processing busi logic of node self
     * @param socketChannel socketChannel
     */
    protected abstract void initNormalHandlers(SocketChannel socketChannel);

    /**
     * init handlers related to char codec
     * @param socketChannel socketChannel
     */
    protected void initCodecHandlers(SocketChannel socketChannel) {
        socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
        socketChannel.pipeline().addLast(new ProtobufDecoder(MessageProtobuf.Message.getDefaultInstance()));
        socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
        socketChannel.pipeline().addLast(new ProtobufEncoder());
    }
}
